import { useState, useEffect } from "react";
import CommonModal from "@/components/CommonModal";
import { Select, Form, message } from "antd";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import { printSuccessNotify, getInboundOrderPrintData, queryLabelTemplate } from "../service";
import { getExpressRelativePrinter, setExpressRelativePrinter, getGlobalConfig, setGlobalConfig } from "@/utils/authority";
import { getAllPrinter } from "@/utils/print.jsx";
import { printKmUniqcode } from '@/utils/printKm.js';

const PrintModal = ({ handleCancel, filteredArray }) => {

	const printObj = getExpressRelativePrinter() || {};

	//模板列表
	const templateObj = getGlobalConfig('PRINT_TEMPLATE_CACHE');

	const [form] = Form.useForm();

	//是否正在打印
	const [isPrint, setIsPrint] = useState(false);

	const [open, setOpen] = useState(false);

	const [printList, setPrintList] = useState([]);

	//模板列表
	const [templateList, setTemplateList] = useState([]);

	//打印数量
	const printNum = filteredArray.reduce((pre, next) => pre + (next.originalNum - next.actualNum), 0);

	useEffect(() => {
		setOpen(true);
		getTemplateList();
		getAllPrinter(val => {
			setPrintList(val);
		});
		form.setFieldsValue({
			printer: printObj["入库标签"]
		});
	}, []);

	//获取模板列表
	const getTemplateList = async () => {
		START_LOADING();
		const { success, data } = await queryLabelTemplate({
			labelType: 10
		})
		if (success) {
			const isTemplate = data.filter(v => v.kmTemplateCode == templateObj['入库标签']).length > 0;
			if(isTemplate) {
				form.setFieldsValue({
					kmTemplateCode: templateObj["入库标签"]
				});
			}
			setTemplateList(data);
		}
		END_LOADING();
	}

	//获取打印数据推入队列
	const onOk = () => {
		if (!filteredArray?.length) {
			return message.info("打印数据为空");
		}
		form.validateFields().then(async value => {
			if (!value) {
				return message.info("请选择打印机");
			}
			if (isPrint) {
				return message.info('打印作业正在进行中，请勿重复提交');
			}
			START_LOADING();
			const arr = filteredArray.map(v => v.inboundOrderNo);
			const res = await getInboundOrderPrintData({
				orderNoList: arr,
				kmTemplateCode: value.kmTemplateCode
			});
			END_LOADING();
			if (res.success) {
				setIsPrint(true);
				message.info('即将开始打印');
				printKmUniqcode(JSON.parse(res.data), value["printer"], () => {
					updatePrintStatus();
					setIsPrint(false);
					setOpen(false);
				});
			}
		});
	};

	//更新打印状态
	const updatePrintStatus = () => {
		const arr = filteredArray.map(v => {
			return {
				inboundOrder: v.inboundOrderNo,
				printNum: v.originalNum
			}
		})
		printSuccessNotify(arr);
	}

	const onCancel = () => {
		setOpen(false);
	}

	const afterClose = () => {
		handleCancel();
	}

	// 设置打印机名称
	const handlePrinterName = name => {
		setExpressRelativePrinter({
			...printObj,
			"入库标签": name
		});
	};

	// 设置标签模板
	const changeTemplate = code => {
		setGlobalConfig('PRINT_TEMPLATE_CACHE', {
			...templateObj,
			"入库标签": code
		});
	};

	const options = (
		Array.isArray(printList) &&
		printList.map(d => (
			<Option key={d} value={d}>
				{d}
			</Option>
		))
	)

	//入库单模板列表
	const tempOptions = (
		Array.isArray(templateList) &&
		templateList.map(d => (
			<Option key={d.kmTemplateCode} value={d.kmTemplateCode}>
				{d.templateName}
			</Option>
		))
	)

	return (
		<CommonModal
			title="打印入库标签"
			open={open}
			onCancel={onCancel}
			width="553px"
			onOk={onOk}
			afterClose={afterClose}
		>
			<Form form={form} name="common-printer-select">
				<SubTitle symbol as="s2" title={`打印入库标签详情`} wrapStyle={{ marginBottom: 16 }} />
				<Form.Item style={{ margin: 8 }}>
					<div>
						<span>标签数量：</span>
						<span style={{ color: "rgba(240, 61, 41, 1)" }}>{printNum}</span>
					</div>
				</Form.Item>
				<Form.Item label="" name="printer" style={{ margin: 8 }} rules={[{ required: true, message: "请先选择打印机" }]}>
					<Select placeholder="请选择打印机" onChange={handlePrinterName}>
						{options}
					</Select>
				</Form.Item>
				<Form.Item label="" name="kmTemplateCode" style={{ margin: '24px 8px 0' }} rules={[{ required: true, message: "请先选择入库单标签模板" }]}>
					<Select placeholder="请选择入库单标签模板" onChange={changeTemplate}>
						{tempOptions}
					</Select>
				</Form.Item>
			</Form>
		</CommonModal>
	);
};

export default PrintModal;
